package me.pplay.playtalk.net;

import me.pplay.playtalk.data.Globals;
import me.pplay.playtalk.database.UserInfoDb;
import me.pplay.playtalk.protocol.bean.TPBuddyinfo;
import android.content.Context;
import android.content.SharedPreferences;

public class SkyidOperation {
	private static final String SHAREPREF_KEY 	= "skyid_info";
	private static final String SID 			= "sid";
	private static final String USERNAME 		= "username";
	private static final String PASSWORD 		= "password";
	
	private static UserInfoDb dbUserinfo;
	
	private static SharedPreferences getSharedPreferences(Context context){
		return context.getSharedPreferences(SHAREPREF_KEY, 0);
	}
	
	public static int getSid(Context context) {
		return getSharedPreferences(context).getInt(SID, -1);
	}
	
	public static void saveSkyid(Context context){
		if(Globals.skyid == -1) {
			return;
		}
		SharedPreferences spf	= getSharedPreferences(context);
		int skyid = spf.getInt(SID, -1);
		if(skyid != Globals.skyid) {
			spf.edit().putInt(SID, Globals.skyid).commit();
		}
	}
	

	public static String getUserName(Context context) {
		return getSharedPreferences(context).getString(USERNAME, "");
	}
	
	public static void saveUserName(Context context, String uname){
		if(uname == null || "" .equals(uname)) {
			return;
		}
		SharedPreferences sharePerf = getSharedPreferences(context);
		String uName = sharePerf.getString(USERNAME, "");
		if(!uName.endsWith(uname)) {
			sharePerf.edit().putString(USERNAME, uname).commit();
		}
	}
	
	public static String getPassword(Context context) {
		return getSharedPreferences(context).getString(PASSWORD, "");
	}
	
	public static void savePassword(Context context, String password){
		if(password == null || "" .equals(password)) {
			return;
		}
		SharedPreferences sharePerf = getSharedPreferences(context);
		String pwd = sharePerf.getString(PASSWORD, "");
		if(!pwd.endsWith(password)) {
			sharePerf.edit().putString(PASSWORD, password).commit();
		}
	}
	
	
	
	public static void saveTpBuddyInfo(TPBuddyinfo tpBuddyinfo, Context context){
		if(tpBuddyinfo == null)
			return;
		if(dbUserinfo == null)
			dbUserinfo = new UserInfoDb(context);
		boolean bool   = dbUserinfo.isExists(tpBuddyinfo.getSkyid());
		if(bool)
			dbUserinfo.update(tpBuddyinfo);
		else
			dbUserinfo.add(tpBuddyinfo);
	}

	public static TPBuddyinfo getTpBuddyInfo(Context context, int skyid){
		if(Globals.myInfo != null && Globals.skyid == skyid)
			return Globals.myInfo;
		if(dbUserinfo == null)
			dbUserinfo = new UserInfoDb(context);
		return dbUserinfo.query(skyid);
	}
}
